<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>手写Promise</title>
</head>

<body>
  <h2>异步任务-函数封装</h2>
  <script>
    /**
     * 异步任务-函数封装
     *  1. 定义函数
     *  2. 调用核心api(queueMicrotask,MutationObserver,setTimeout)
     *  3. 使用封装函数
     * */
    // 1. 定义函数
    function runAsynctask(callback) {
      // 2. 调用核心api(queueMicrotask,MutationObserver,setTimeout)
      if (typeof queueMicrotask === 'function') {
        queueMicrotask(callback)
      } else if (typeof MutationObserver === 'function') {
        const obs = new MutationObserver(callback)
        const divNode = document.createElement('div')
        obs.observe(divNode, { childList: true })
        divNode.innerText = 'itheima666'
      } else {
        setTimeout(callback, 0)
      }
    }


    // // ------------- 测试代码1 封装函数 -------------
    // console.log('1')
    // runAsynctask(() => {
    //   console.log('runAsynctask')
    // })
    // console.log('2')


    const PENDING = 'pending'
    const FULFILLED = 'fulfilled'
    const REJECTED = 'rejected'
    class HMPromise {
      // 状态
      state = PENDING
      // 原因
      result = undefined
      // 回调函数数组
      #handlers = [] // [{onFulfilled,onRejected}...]

      // 构造函数
      constructor(func) {
        // pending->fulfilled
        const resolve = (result) => {
          if (this.state === PENDING) {
            this.state = FULFILLED
            this.result = result
            this.#handlers.forEach(({ onFulfilled }) => {
              onFulfilled(this.result)
            })
          }
        }
        // pending->rejected
        const reject = (result) => {
          if (this.state === PENDING) {
            this.state = REJECTED
            this.result = result
            this.#handlers.forEach(({ onRejected }) => {
              onRejected(this.result)
            })
          }
        }
        func(resolve, reject)
      }

      // then方法
      then(onFulfilled, onRejected) {
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x
        onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }

        // 3. 使用封装函数
        if (this.state === FULFILLED) {
          runAsynctask(() => {
            onFulfilled(this.result)
          })
        } else if (this.state === REJECTED) {
          runAsynctask(() => {
            onRejected(this.result)
          })
        } else if (this.state === PENDING) {
          this.#handlers.push({
            onFulfilled: () => {
              runAsynctask(() => {
                onFulfilled(this.result)
              })
            }, onRejected: () => {
              runAsynctask(() => {
                onRejected(this.result)
              })
            }
          })
        }
      }
    }



    // ------------- 测试代码2 异步任务 -------------
    console.log('top')
    const p = new HMPromise((resolve, reject) => {
      // resolve('success')
      reject('error')
    })
    p.then(res => {
      console.log(res)
    }, err => {
      console.log(err)
    })
    console.log('bottom')











  </script>
</body>

</html>